package com.sinosoft.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import com.sinosoft.dto.User;
import com.sinosoft.service.UserService;

public class UserRealm extends AuthorizingRealm{

	@Autowired
	private UserService userService;
	
	/**
	 * 执行授权逻辑
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		System.out.println("执行授权逻辑");
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		
		Subject subject =SecurityUtils.getSubject();
		User user = (User) subject.getPrincipal();
		info.addStringPermission(user.getPerms());
		return info;
	}

	/**
	 * 执行认证逻辑
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
		System.out.println("执行认证逻辑");
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)arg0;
		User user = userService.findByName(usernamePasswordToken.getUsername());
		
		
		if(!usernamePasswordToken.getUsername().equals(user.getName())) {
			return null;
		}
		// 返回login的数据 、数据库密码 、shiro的名称
		return new SimpleAuthenticationInfo(user,user.getPassword(),"");
	}

}
